package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
import android.os.ParcelUuid;
import android.util.Log;
import android.view.Window;
import android.widget.Switch;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        t();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void t() {
        //初始化广播设置
        AdvertiseSettings mAdvertiseSettings = new AdvertiseSettings.Builder()
                //设置广播模式，以控制广播的功率和延迟。
//                .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_POWER)
                .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED)
                //发射功率级别
//                .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)
                //不得超过180000毫秒。值为0将禁用时间限制。
                .setTimeout(0)
                //设置是否可以连接
                .setConnectable(false)
                .build();

        byte[] y = hexStringToBytes("15FDA50693A4E24FB1AFCFC6EB0764782527D6B052");

        //初始化广播包
        AdvertiseData mAdvertiseData = new AdvertiseData.Builder()
                //设置广播设备名称
                .setIncludeDeviceName(false)
                .addManufacturerData(0x4c,y)
                //设置发射功率级别
                .setIncludeDeviceName(false)
                .build();
//        byte[] x =hexToByteArr("0215FDA50693A4E24FB1AFCFC6EB0764782527D6B052C500");
        byte[] z = hexToBytes("0215FDA50693A4E24FB1AFCFC6EB0764782527D6B052C500");

//初始化扫描响应包
        AdvertiseData mScanResponseData = new AdvertiseData.Builder()
                //隐藏广播设备名称
                .setIncludeDeviceName(false)
                //隐藏发射功率级别
                .setIncludeDeviceName(true)
                .addManufacturerData(0x004c,y)
                //设置广播的服务`UUID`
//                .addServiceData(serviceUUID,hexToByteArr("0201061AFF4C000215FDA50693A4E24FB1AFCFC6EB0764782527D6B052C500"))
                //设置厂商数据
                .build();
//        AdvertiseData iBeaconAdvertiseData = createIBeaconAdvertiseData(serviceUUID, (short) 10198, (short) 45138, (byte) 59);
                AdvertiseData iBeaconAdvertiseData = createAdvertiseData("fda50693-a4e2-4fb1-afcf-c6eb07647825",(short) 10198, (short) 45138, (byte) -59,null,null);
//        createAdvertiseData(beaconUuid, (short)10028, (short)60350, (byte) -59, serviceDataUuid, data),

                //获取蓝牙设配器
        BluetoothManager bluetoothManager = (BluetoothManager)
                getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();
//设置设备蓝牙名称
        mBluetoothAdapter.setName("daqi");

        //获取BLE广播的操作对象。
//如果蓝牙关闭或此设备不支持蓝牙LE广播，则返回null。
        BluetoothLeAdvertiser mBluetoothLeAdvertiser = mBluetoothAdapter.getBluetoothLeAdvertiser();
        SampleAdvertiseCallback mAdvertiseCallback = new SampleAdvertiseCallback();
//mBluetoothLeAdvertiser不为空，且蓝牙已开打
        if (mBluetoothAdapter.isEnabled()) {
            if (mBluetoothLeAdvertiser != null) {
                //开启广播
//                mBluetoothLeAdvertiser.startAdvertising(mAdvertiseSettings,
//                        mAdvertiseData, mScanResponseData, mAdvertiseCallback);
                mBluetoothLeAdvertiser.startAdvertising(mAdvertiseSettings, iBeaconAdvertiseData, mAdvertiseCallback);
            } else {
                Log.d("daqi", "该手机不支持ble广播");
            }
        } else {
            Log.d("daqi", "手机蓝牙未开启");


        }
    }

    private class SampleAdvertiseCallback extends AdvertiseCallback {

        @Override
        public void onStartFailure(int errorCode) {
            super.onStartFailure(errorCode);
            Log.d("daqi","开启服务失败，失败码 = " + errorCode);
        }

        @Override
        public void onStartSuccess(AdvertiseSettings settingsInEffect) {
            super.onStartSuccess(settingsInEffect);
            Log.d("daqi","开启服务成功");
        }
    }

    private class daqiAdvertiseCallback extends AdvertiseCallback {
        //开启广播成功回调
        @Override
        public void onStartSuccess(AdvertiseSettings settingsInEffect){
            super.onStartSuccess(settingsInEffect);
            Log.d("daqi","开启服务成功");
        }

        //无法启动广播回调。
        @Override
        public void onStartFailure(int errorCode) {
            super.onStartFailure(errorCode);
            Log.d("daqi","开启服务失败，失败码 = " + errorCode);
        }
    }

    public static byte[] hexStringToBytes(String hexString) {

        hexString = hexString.toLowerCase();
        final byte[] byteArray = new byte[hexString.length() >> 1];
        int index = 0;
        for (int i = 0; i < hexString.length(); i++) {
            if (index  > hexString.length() - 1) {
                return byteArray;
            }
            byte highDit = (byte) (Character.digit(hexString.charAt(index), 16) & 0xFF);
            byte lowDit = (byte) (Character.digit(hexString.charAt(index + 1), 16) & 0xFF);
            byteArray[i] = (byte) (highDit << 4 | lowDit);
            index += 2;
        }
        return byteArray;
    }


    public static byte[] hexToBytes(String hex)
    {
        int hexLength = hex.length();
        byte[] result;
        //判断Hex字符串长度，如果为奇数个需要在前边补0以保证长度为偶数
        //因为Hex字符串一般为两个字符，所以我们在截取时也是截取两个为一组来转换为Byte。
        if (hexLength % 2 ==1)
        {
            //奇数
            hexLength++;
            hex = "0"+hex;
        }
        result = new byte[(hexLength/2)];
        int j = 0;
        for (int i = 0; i < hexLength; i+=2) {
            result[j] = hexToByte(hex.substring(i,i+2));
            j++;
        }
        return result;
    }
    public static byte hexToByte(String hex)
    {
        return (byte) Integer.parseInt(hex,16);
    }

    private static byte toByte(char c) {
        byte b = (byte) "0123456789ABCDEF".indexOf(c);
        return b;
    }



    /**
     * iBeacon 的 ManufacturerData（厂商自定义信息）
     * 01 byte	type = 0x02 指明它是 iBeacon 帧
     * 01 byte	len = 0x15 = 21
     * 16 byte	UUID
     * 02 byte	major
     * 02 byte	minor
     * 01 byte	tx power
     */
    private AdvertiseData createAdvertiseData(String beaconUuidStr, short major, short minor, byte txPower, String serviceDataUuidStr, String serviceData) {
        //Beacon 标识符
        byte beaconType = 0x02;
        //Beacon 厂商自定义信息长度
        byte beaconLen = 0x15;
        //Company: Apple, Inc. <0x004C>
        byte manufacturerId = 0x004c;

        UUID beaconUuid = UUID.fromString(beaconUuidStr);

        byte[] manufacturerSpecificData = new byte[23];
        ByteBuffer bb = ByteBuffer.wrap(manufacturerSpecificData);
        bb.order(ByteOrder.BIG_ENDIAN);
        bb.put(beaconType)
                .put(beaconLen)
                .putLong(beaconUuid.getMostSignificantBits())
                .putLong(beaconUuid.getLeastSignificantBits())
                .putShort(major)
                .putShort(minor)
                .put(txPower);

        AdvertiseData.Builder builder = new AdvertiseData.Builder();
        //广播服务的UUID
//    		builder.addServiceUuid(uuid)
        //添加服务数据UUID和服务数据
//    		builder.addServiceData(ParcelUuid.fromString(serviceDataUuidStr), str2bcd(serviceData))
        //添加制造商ID和数据
        builder.addManufacturerData(manufacturerId, manufacturerSpecificData)
                //广播是否包含设备名
                .setIncludeDeviceName(false)
                //广播是否包含发射功率等级
                .setIncludeTxPowerLevel(false);

        return builder.build();
    }
}


